package com.shop.cereshop.app.dl.logic.service.Impl;

import com.shop.cereshop.app.dao.buyer.CereBuyerWithdrawalDAO;
import com.shop.cereshop.app.dao.distributor.CereShopCommissionRecordDao;
import com.shop.cereshop.app.dao.distributor.CereShopDistributorDAO;
import com.shop.cereshop.app.dl.logic.demo.CertHttpUtil;
import com.shop.cereshop.app.dl.logic.demo.IpKit;
import com.shop.cereshop.app.dl.logic.domain.CereShopCommissionRecord;
import com.shop.cereshop.app.service.buyer.CereBuyerUserService;
import com.shop.cereshop.commons.domain.buyer.CereBuyerUser;
import com.shop.cereshop.app.dl.logic.service.ChangeService;
import com.shop.cereshop.app.dl.logic.utils.ResultInfo;
import com.shop.cereshop.app.service.log.CerePlatformLogService;
import com.shop.cereshop.app.weixin.skd.WXPayUtil;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.domain.buyer.CereBuyerWithdrawal;
import com.shop.cereshop.commons.domain.distributor.CereShopDistributor;
import com.shop.cereshop.commons.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * @program: dlshop
 * 描述：
 * @author: 我好帅
 * @create: 2021-07-22 16:12
 **/
@Service
@Slf4j(topic = "ChangeServiceImpl")
public class ChangeServiceImpl implements ChangeService {

    @Value("${weixin.appid}")
    private String APPID;
    @Value("${weixin.mchid}")
    private String MCHID;
    @Value("${weixin.certurl}")
    private String CERTPATH;
    @Value("${weixin.key}")
    private String PATERNERKEY;
    @Value("${Detail.expenditure.withdraw}")
    private String withdraw;
    @Value("${withdrawalDesc}")
    private String withdrawalDesc;

    @Autowired
    private CertHttpUtil certHttpUtil;

    @Autowired
    private CereBuyerWithdrawalDAO cereBuyerWithdrawalDAO;
    @Autowired
    private CerePlatformLogService cerePlatformLogService;
    @Autowired
    private CereShopDistributorDAO cereShopDistributorDAO;
    @Autowired
    private CereShopCommissionRecordDao cereShopCommissionRecordDao;


    @Override
    public ResultInfo transfer(HttpServletRequest request, BigDecimal money, String openID, CereBuyerUser user) {
        // 1.0 拼凑企业支付需要的参数
        String appid = APPID; // APP对应的微信的appid
        String mch_id = MCHID; // 商户号
        String nonce_str = WXPayUtil.generateNonceStr(); // 生成随机数
        String partner_trade_no = WXPayUtil.generateNonceStr(); // 生成商户订单号
        String openid = openID; // 收款用户openid
        String check_name = "NO_CHECK"; // 是否验证真实姓名呢
        String re_user_name = "KOLO"; // 收款用户姓名(非必须)
        Integer m = money.intValue();
        String amount = String.valueOf(m); // 企业付款金额，最少为100，单位为分
        String desc = withdrawalDesc; // 企业付款操作说明信息。必填。
        String spbill_create_ip = IpKit.getIpAddr(request); // 用户的ip地址

        // 2.0 生成map集合
        SortedMap<String, String> packageParams = new TreeMap<String, String>();
        packageParams.put("mch_appid", appid); // 微信公众号的appid
        packageParams.put("mchid", mch_id); // 商务号
        packageParams.put("nonce_str", nonce_str); // 随机生成后数字，保证安全性

        packageParams.put("partner_trade_no", partner_trade_no); // 生成商户订单号
        packageParams.put("openid", openid); // 支付给用户openid
        packageParams.put("check_name", check_name); // 是否验证真实姓名呢
        packageParams.put("re_user_name", re_user_name);// 收款用户姓名
        packageParams.put("amount", amount); // 企业付款金额，单位为分
        packageParams.put("desc", desc); // 企业付款操作说明信息。必填。
        packageParams.put("spbill_create_ip", spbill_create_ip); // 调用接口的机器Ip地址

        try {

            // 3.0 利用上面的参数，先去生成自己的签名
            String sign = WXPayUtil.generateSignature(packageParams, PATERNERKEY);

            // 4.0 将签名再放回map中，它也是一个参数
            packageParams.put("sign", sign);

            // 5.0将当前的map结合转化成xml格式
            String xml = WXPayUtil.mapToXml(packageParams);

            // 6.0获取需要发送的url地址
            String wxUrl = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers"; // 获取退款的api接口


            System.out.println("发送前的xml为：" + xml);
            log.info("发送前的xml为：" + xml);

            // 7,向微信发送请求转账请求
            String returnXml = certHttpUtil.postData(wxUrl, xml, MCHID, CERTPATH);

            System.out.println("返回的returnXml为:" + returnXml);
            log.info("返回的returnXml为：" + returnXml);
            // 8，将微信返回的xml结果转成map格式
            Map<String, String> returnMap = WXPayUtil.xmlToMap(returnXml);

            if (returnMap.get("result_code").equals("SUCCESS")) {
                // 付款成功
                System.out.println("returnMap为:" + returnMap);
                log.info("付款成功:" + returnMap);
                CereBuyerWithdrawal withdrawal = new CereBuyerWithdrawal();
                String time = TimeUtils.yyMMddHHmmss();
                withdrawal.setApplyTime(time);
                withdrawal.setState(IntegerEnum.BUYER_WITHDRAWAL_SUCCESS.getCode());
                withdrawal.setBuyerUserId(user.getBuyerUserId());
                withdrawal.setBankName("提现到零钱");
                withdrawal.setBankCard("0");
                withdrawal.setWithdrawalMoney(money);
                withdrawal.setType(1);
                cereBuyerWithdrawalDAO.insert(withdrawal);
                //新增日志
                cerePlatformLogService.addLog(user, "账户模块", "客户端操作", "发起提现申请", withdrawal.getWithdrawalId(), time);
                //...查询分销员信息,需要分销员表中用户id不为空

                CereShopDistributor cereShopDistributor = cereShopDistributorDAO.findByBuyerUserId(withdrawal.getBuyerUserId());
                //添加提现支出记录
                CereShopCommissionRecord record = new CereShopCommissionRecord();
                record.setCommission(withdrawal.getWithdrawalMoney().multiply(new BigDecimal(-1)));
                record.setState(2);
                record.setDistributorId(cereShopDistributor.getDistributorId());
                record.setDetail(withdraw);
                record.setCreateTime(time);
                cereShopCommissionRecordDao.insertSelective(record);
            } else {
                log.info("902信息:" + returnMap.get("err_code_des"));
                return ResultInfo.error(902, returnMap.get("err_code_des"));
            }
            return ResultInfo.ok(returnMap.toString());
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            log.info("转账失败");
            return ResultInfo.error(901, "微信转账失败！");
        }
    }
}
